<?php

/* INSERT VALUES INTO DATABASE */

echo "<p>Adding...\n";

/* Building sql String */
$sql = "INSERT INTO $tableName (";
for ($i=1; $i < $fields; $i++) {
        if ($i!=1) {
                $sql = $sql . ", ";
        }
        $name  = mysql_field_name($result, $i);
        $sql = $sql . $name;
}
$sql = $sql . ") VALUES (";
for ($i=1; $i < $fields; $i++) {
        if ($i!=1) {
                $sql = $sql . ", ";
        }
        if ($plain[$i]!="") {
		$sql = $sql . "'" . $plain[$i] . "'";
	} else {
		$sql = $sql . "NULL";
	}
}
$sql = $sql . ")";
//echo $sql . "<br />\n";

/* Submitting Query */
if (!mysql_query($sql,$con))
{

/* Print Error Message */
//echo "<p>".mysql_error()."</p>";

/* Get Column name of null error*/
$regExp1 = "/^Column\s\'([^\']*)\'\scannot\sbe\snull$/";
$regExp2 = "/^([^`]*)`([^`]*)`.`([^`]*)`, CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)\)$/";
$matches = array();
if (mysql_errno()==1048) {
	preg_match($regExp1, mysql_error(), $matches);
	$error_field=$matches[1];
} else if (mysql_errno()==1452) {
	preg_match($regExp2, mysql_error(), $matches);
	$error_field=$matches[5];
} else {
	$error_field="";
}
//echo var_dump($matches);

/* Print Error message */
echo "</p><p class=\"error-message\">Error: System is unable to add data! ";
if ($error_field!="") {
	echo "Please review field \"" . $error_field . "\".</p>";
} else echo "Please review and change inputted fields and try again.</p>";

  if ($_POST['Submit']=='Make Copy') {
	if ($_GET['input'] == 'plain') {
		$_POST['Submit'] = 'Plain Text Edit';
	} else {
		$_POST['Submit'] = 'Form Edit';
	}
  }  else if ($_POST['Submit']=='Add Data') {
	if ($_GET['input'] == 'plain') {
		$_POST['Submit'] = 'Plain Text Input';
	} else {
		$_POST['Submit'] = 'Form Input';
	}
  }
}
else echo "Data saved!</p>\n";


?>
